package com.miaomiaojia.waterfallfetch;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.miaomiaojia.waterfallcache.CacheUtils;
import com.miaomiaojia.waterfallcache.DiskLruCache;

import android.content.Context;

public class CacheFetch {
	/**
	 * 涓嬭浇鍥剧墖骞朵笖鍔犲叆杩�lru 缂撳瓨閲岄潰
	 * 
	 * @param context
	 * @param urlString
	 * @return
	 */
	public static File dowanLoadBitmap(Context context, String urlString) {
		final File cacheDir = DiskLruCache.getDiskCacheDir(context,
				CacheUtils.HTTP_CACHE_DIR);
		final DiskLruCache cache = DiskLruCache.openCache(context, cacheDir,
				CacheUtils.HTTP_CACHE_SIZE);
		final File cacheFile = new File(cache.createFilePath(urlString));

		if (cache.containsKey(urlString)) {
			CacheUtils.Debug(cacheFile.toString()
					+ "downloadBitmap - found in http cache - " + urlString);
			return cacheFile;
		}

		CacheUtils.Debug("downloadBitmap - downloading - " + urlString);
		CacheUtils.disableConnectionReuseIfNecessary();

		HttpURLConnection urlConnection = null;
		BufferedOutputStream out = null;

		try {
			final URL url = new URL(urlString);
			urlConnection = (HttpURLConnection) url.openConnection();
			System.setProperty("http.keepAlive", "false");
			InputStream inStream = urlConnection.getInputStream();
			final InputStream in = new BufferedInputStream(inStream,
					CacheUtils.IO_BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(cacheFile),
					CacheUtils.IO_BUFFER_SIZE);

			CacheUtils.CopyStream(in, out);
			return cacheFile;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();
			}
			if (out != null) {
				try {
					out.close();
				} catch (final IOException e) {
					CacheUtils.Debug("Error in downloadBitmap - " + e);
				}
			}
		}

		return null;
	}
}
